<template>
  <div class="completed-tasks-container">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-left">
        <h2>已办任务</h2>
        <p>我已经处理完成的审批任务</p>
      </div>
      <div class="header-right">
        <el-button type="primary" @click="exportData">
          <el-icon><Download /></el-icon>
          导出数据
        </el-button>
      </div>
    </div>

    <!-- 统计卡片 -->
    <div class="stats-cards">
      <div class="stat-card approved">
        <div class="stat-icon">
          <el-icon><Check /></el-icon>
        </div>
        <div class="stat-content">
          <div class="stat-number">{{ approvedCount }}</div>
          <div class="stat-label">已同意</div>
        </div>
      </div>
      <div class="stat-card rejected">
        <div class="stat-icon">
          <el-icon><Close /></el-icon>
        </div>
        <div class="stat-content">
          <div class="stat-number">{{ rejectedCount }}</div>
          <div class="stat-label">已拒绝</div>
        </div>
      </div>
      <div class="stat-card returned">
        <div class="stat-icon">
          <el-icon><RefreshLeft /></el-icon>
        </div>
        <div class="stat-content">
          <div class="stat-number">{{ returnedCount }}</div>
          <div class="stat-label">已退回</div>
        </div>
      </div>
      <div class="stat-card efficiency">
        <div class="stat-icon">
          <el-icon><TrendCharts /></el-icon>
        </div>
        <div class="stat-content">
          <div class="stat-number">{{ avgProcessTime }}h</div>
          <div class="stat-label">平均处理时间</div>
        </div>
      </div>
    </div>

    <!-- 筛选区域 -->
    <div class="filter-section">
      <el-input
        v-model="searchKeyword"
        placeholder="搜索任务"
        style="width: 300px; margin-right: 15px;"
        clearable
      >
        <template #prefix>
          <el-icon><Search /></el-icon>
        </template>
      </el-input>
      <el-select v-model="resultFilter" placeholder="审批结果" style="width: 120px; margin-right: 15px;">
        <el-option label="全部" value=""></el-option>
        <el-option label="已同意" value="approved"></el-option>
        <el-option label="已拒绝" value="rejected"></el-option>
        <el-option label="已退回" value="returned"></el-option>
      </el-select>
      <el-select v-model="typeFilter" placeholder="申请类型" style="width: 150px; margin-right: 15px;">
        <el-option label="全部" value=""></el-option>
        <el-option label="请假申请" value="请假申请"></el-option>
        <el-option label="加班申请" value="加班申请"></el-option>
        <el-option label="报销申请" value="报销申请"></el-option>
        <el-option label="调休申请" value="调休申请"></el-option>
        <el-option label="出差申请" value="出差申请"></el-option>
        <el-option label="采购申请" value="采购申请"></el-option>
      </el-select>
      <el-date-picker
        v-model="dateRange"
        type="daterange"
        range-separator="至"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
        style="width: 240px;"
      ></el-date-picker>
    </div>

    <!-- 任务列表 -->
    <div class="tasks-table">
      <el-table :data="filteredTasks" style="width: 100%" stripe>
        <el-table-column prop="title" label="申请标题" width="200" show-overflow-tooltip></el-table-column>
        <el-table-column prop="applicant" label="申请人" width="100"></el-table-column>
        <el-table-column prop="type" label="申请类型" width="120">
          <template #default="{ row }">
            <el-tag :type="getTypeTagType(row.type)">{{ row.type }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="result" label="审批结果" width="100">
          <template #default="{ row }">
            <el-tag :type="getResultTagType(row.result)">{{ getResultText(row.result) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="opinion" label="审批意见" width="200" show-overflow-tooltip></el-table-column>
        <el-table-column prop="completeTime" label="处理时间" width="180">
          <template #default="{ row }">
            {{ formatTime(row.completeTime) }}
          </template>
        </el-table-column>
        <el-table-column label="处理耗时" width="100">
          <template #default="{ row }">
            {{ getProcessDuration(row.receiveTime, row.completeTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150">
          <template #default="{ row }">
            <el-button size="small" @click="viewTaskDetail(row)">查看</el-button>
            <el-button size="small" type="info" @click="viewHistory(row)">历史</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页 -->
    <div class="pagination-section">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="totalTasks"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 任务详情对话框 -->
    <el-dialog
      v-model="showDetailDialog"
      title="任务详情"
      width="700px"
    >
      <div v-if="currentTask" class="task-detail">
        <!-- 申请信息 -->
        <div class="application-info">
          <h4>申请信息</h4>
          <el-descriptions :column="2" border>
            <el-descriptions-item label="申请标题">{{ currentTask.title }}</el-descriptions-item>
            <el-descriptions-item label="申请人">{{ currentTask.applicant }}</el-descriptions-item>
            <el-descriptions-item label="申请类型">
              <el-tag :type="getTypeTagType(currentTask.type)">{{ currentTask.type }}</el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="申请时间">{{ formatTime(currentTask.createTime) }}</el-descriptions-item>
            <el-descriptions-item label="接收时间">{{ formatTime(currentTask.receiveTime) }}</el-descriptions-item>
            <el-descriptions-item label="处理时间">{{ formatTime(currentTask.completeTime) }}</el-descriptions-item>
            <el-descriptions-item label="申请原因" :span="2">{{ currentTask.reason }}</el-descriptions-item>
          </el-descriptions>
        </div>

        <!-- 审批信息 -->
        <div class="approval-info">
          <h4>审批信息</h4>
          <el-descriptions :column="2" border>
            <el-descriptions-item label="审批结果">
              <el-tag :type="getResultTagType(currentTask.result)">{{ getResultText(currentTask.result) }}</el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="处理耗时">{{ getProcessDuration(currentTask.receiveTime, currentTask.completeTime) }}</el-descriptions-item>
            <el-descriptions-item label="审批意见" :span="2">{{ currentTask.opinion }}</el-descriptions-item>
            <el-descriptions-item v-if="currentTask.nextApprover" label="下一审批人">{{ currentTask.nextApprover }}</el-descriptions-item>
            <el-descriptions-item v-if="currentTask.ccUsers && currentTask.ccUsers.length" label="抄送人员">{{ currentTask.ccUsers.join(', ') }}</el-descriptions-item>
          </el-descriptions>
        </div>
      </div>
    </el-dialog>

    <!-- 审批历史对话框 -->
    <el-dialog
      v-model="showHistoryDialog"
      title="审批历史"
      width="800px"
    >
      <div class="approval-history">
        <el-timeline>
          <el-timeline-item
            v-for="(item, index) in approvalHistory"
            :key="index"
            :timestamp="formatTime(item.time)"
            :type="getHistoryItemType(item.action)"
          >
            <div class="history-item">
              <div class="history-header">
                <span class="history-action">{{ item.action }}</span>
                <span class="history-user">{{ item.user }}</span>
              </div>
              <div class="history-content">{{ item.content }}</div>
            </div>
          </el-timeline-item>
        </el-timeline>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Download, Search, Check, Close, RefreshLeft, TrendCharts } from '@element-plus/icons-vue'

// 响应式数据
const searchKeyword = ref('')
const resultFilter = ref('')
const typeFilter = ref('')
const dateRange = ref([])
const currentPage = ref(1)
const pageSize = ref(20)
const totalTasks = ref(0)
const showDetailDialog = ref(false)
const showHistoryDialog = ref(false)
const currentTask = ref(null)

// 已办任务数据
const completedTasks = ref([
  {
    id: 1,
    title: '王五的加班申请',
    applicant: '王五',
    type: '加班申请',
    result: 'approved',
    opinion: '同意加班申请，注意劳逸结合',
    createTime: new Date('2024-01-15 14:30:00'),
    receiveTime: new Date('2024-01-15 16:00:00'),
    completeTime: new Date('2024-01-15 17:30:00'),
    reason: '项目开发需要加班',
    nextApprover: '张总监',
    ccUsers: ['人事部', '行政部']
  },
  {
    id: 2,
    title: '赵六的调休申请',
    applicant: '赵六',
    type: '调休申请',
    result: 'rejected',
    opinion: '调休余额不足，建议申请事假',
    createTime: new Date('2024-01-14 09:00:00'),
    receiveTime: new Date('2024-01-14 09:15:00'),
    completeTime: new Date('2024-01-14 09:20:00'),
    reason: '个人事务需要调休一天',
    ccUsers: ['人事部']
  },
  {
    id: 3,
    title: '孙七的报销申请',
    applicant: '孙七',
    type: '报销申请',
    result: 'approved',
    opinion: '报销单据齐全，同意报销',
    createTime: new Date('2024-01-13 10:30:00'),
    receiveTime: new Date('2024-01-13 15:00:00'),
    completeTime: new Date('2024-01-13 16:10:00'),
    reason: '客户招待费用报销',
    nextApprover: '财务经理',
    ccUsers: ['财务部']
  },
  {
    id: 4,
    title: '李四的请假申请',
    applicant: '李四',
    type: '请假申请',
    result: 'returned',
    opinion: '请假理由不够充分，请补充详细说明',
    createTime: new Date('2024-01-12 11:20:00'),
    receiveTime: new Date('2024-01-12 14:30:00'),
    completeTime: new Date('2024-01-12 15:45:00'),
    reason: '个人事务',
    ccUsers: []
  },
  {
    id: 5,
    title: '张三的出差申请',
    applicant: '张三',
    type: '出差申请',
    result: 'approved',
    opinion: '同意出差，注意安全',
    createTime: new Date('2024-01-11 08:45:00'),
    receiveTime: new Date('2024-01-11 09:00:00'),
    completeTime: new Date('2024-01-11 10:30:00'),
    reason: '客户现场技术支持',
    nextApprover: '总经理',
    ccUsers: ['行政部', '财务部']
  }
])

// 审批历史数据
const approvalHistory = ref([
  {
    action: '发起申请',
    user: '张三',
    time: new Date('2024-01-11 08:45:00'),
    content: '提交出差申请，前往北京进行客户现场技术支持'
  },
  {
    action: '部门经理审批',
    user: '李经理',
    time: new Date('2024-01-11 10:30:00'),
    content: '同意出差，注意安全。已转交总经理审批。'
  },
  {
    action: '总经理审批',
    user: '王总',
    time: new Date('2024-01-11 14:20:00'),
    content: '同意出差申请，预祝工作顺利。'
  },
  {
    action: '流程结束',
    user: '系统',
    time: new Date('2024-01-11 14:21:00'),
    content: '审批流程已完成，申请已通过。'
  }
])

// 计算属性
const filteredTasks = computed(() => {
  let filtered = completedTasks.value
  
  if (searchKeyword.value) {
    filtered = filtered.filter(task => 
      task.title.includes(searchKeyword.value) || 
      task.applicant.includes(searchKeyword.value) ||
      task.opinion.includes(searchKeyword.value)
    )
  }
  
  if (resultFilter.value) {
    filtered = filtered.filter(task => task.result === resultFilter.value)
  }
  
  if (typeFilter.value) {
    filtered = filtered.filter(task => task.type === typeFilter.value)
  }
  
  if (dateRange.value && dateRange.value.length === 2) {
    const [startDate, endDate] = dateRange.value
    filtered = filtered.filter(task => {
      const completeTime = new Date(task.completeTime)
      return completeTime >= startDate && completeTime <= endDate
    })
  }
  
  return filtered
})

const approvedCount = computed(() => {
  return completedTasks.value.filter(task => task.result === 'approved').length
})

const rejectedCount = computed(() => {
  return completedTasks.value.filter(task => task.result === 'rejected').length
})

const returnedCount = computed(() => {
  return completedTasks.value.filter(task => task.result === 'returned').length
})

const avgProcessTime = computed(() => {
  const totalTime = completedTasks.value.reduce((sum, task) => {
    const duration = new Date(task.completeTime) - new Date(task.receiveTime)
    return sum + duration
  }, 0)
  const avgMs = totalTime / completedTasks.value.length
  return Math.round(avgMs / (1000 * 60 * 60) * 10) / 10 // 转换为小时，保留一位小数
})

// 方法
const getTypeTagType = (type) => {
  const typeMap = {
    '请假申请': 'primary',
    '加班申请': 'success',
    '报销申请': 'warning',
    '调休申请': 'info',
    '出差申请': '',
    '采购申请': 'danger'
  }
  return typeMap[type] || 'default'
}

const getResultTagType = (result) => {
  const resultMap = {
    'approved': 'success',
    'rejected': 'danger',
    'returned': 'warning'
  }
  return resultMap[result] || 'default'
}

const getResultText = (result) => {
  const resultMap = {
    'approved': '已同意',
    'rejected': '已拒绝',
    'returned': '已退回'
  }
  return resultMap[result] || result
}

const formatTime = (time) => {
  if (!time) return ''
  return new Date(time).toLocaleString('zh-CN')
}

const getProcessDuration = (receiveTime, completeTime) => {
  if (!receiveTime || !completeTime) return ''
  const duration = new Date(completeTime) - new Date(receiveTime)
  const hours = Math.floor(duration / (1000 * 60 * 60))
  const minutes = Math.floor((duration % (1000 * 60 * 60)) / (1000 * 60))
  
  if (hours > 0) {
    return `${hours}小时${minutes}分钟`
  } else {
    return `${minutes}分钟`
  }
}

const getHistoryItemType = (action) => {
  const typeMap = {
    '发起申请': 'primary',
    '部门经理审批': 'success',
    '总经理审批': 'success',
    '流程结束': 'info',
    '审批拒绝': 'danger',
    '审批退回': 'warning'
  }
  return typeMap[action] || 'primary'
}

const exportData = () => {
  ElMessage.success('数据导出功能开发中...')
}

const viewTaskDetail = (task) => {
  currentTask.value = task
  showDetailDialog.value = true
}

const viewHistory = (task) => {
  currentTask.value = task
  showHistoryDialog.value = true
  // 这里可以根据任务ID获取具体的审批历史
}

const handleSizeChange = (val) => {
  pageSize.value = val
  // 重新加载数据
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  // 重新加载数据
}

// 生命周期
onMounted(() => {
  totalTasks.value = completedTasks.value.length
})
</script>

<style scoped>
.completed-tasks-container {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.header-left h2 {
  margin: 0 0 5px 0;
  color: #333;
  font-size: 24px;
}

.header-left p {
  margin: 0;
  color: #666;
  font-size: 14px;
}

.stats-cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 20px;
  margin-bottom: 20px;
}

.stat-card {
  display: flex;
  align-items: center;
  padding: 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.stat-card.approved {
  border-left: 4px solid #67c23a;
}

.stat-card.rejected {
  border-left: 4px solid #f56c6c;
}

.stat-card.returned {
  border-left: 4px solid #e6a23c;
}

.stat-card.efficiency {
  border-left: 4px solid #409eff;
}

.stat-icon {
  font-size: 32px;
  margin-right: 15px;
  color: #666;
}

.stat-content {
  flex: 1;
}

.stat-number {
  font-size: 24px;
  font-weight: bold;
  color: #333;
  margin-bottom: 5px;
}

.stat-label {
  font-size: 14px;
  color: #666;
}

.filter-section {
  margin-bottom: 20px;
  padding: 15px 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.tasks-table {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  overflow: hidden;
  margin-bottom: 20px;
}

.pagination-section {
  text-align: right;
  padding: 15px 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.task-detail {
  padding: 10px 0;
}

.application-info,
.approval-info {
  margin-bottom: 20px;
}

.application-info h4,
.approval-info h4 {
  margin: 0 0 15px 0;
  color: #333;
  font-size: 16px;
  font-weight: 600;
}

.approval-info {
  border-top: 1px solid #eee;
  padding-top: 20px;
}

.approval-history {
  padding: 10px 0;
}

.history-item {
  margin-bottom: 10px;
}

.history-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 5px;
}

.history-action {
  font-weight: 600;
  color: #333;
}

.history-user {
  color: #666;
  font-size: 14px;
}

.history-content {
  color: #666;
  line-height: 1.5;
}

:deep(.el-table) {
  border-radius: 0;
}

:deep(.el-table th) {
  background-color: #f8f9fa;
  color: #333;
  font-weight: 600;
}

:deep(.el-table td) {
  padding: 12px 0;
}

:deep(.el-button + .el-button) {
  margin-left: 8px;
}

:deep(.el-timeline-item__timestamp) {
  color: #909399;
  font-size: 12px;
}
</style>